<?php
/**
 * Проверка капчи
 * @author dizews
 *
 * @todo банн пользователей по достижении максимального количества попыток НЕ РЕАЛИЗОВАН
 *
 */

class Validate_Captcha extends Zend_Validate_Abstract {

	const INVALID = 'CaptchaInvalid';
	const LAST_TRIES = 'LastTries';

	protected $_caseIgnore = false;

	protected $_messageTemplates = array(
		self::INVALID => 'Вы ввели неверный код',
		self::LAST_TRIES => 'Осталось %last_tries% попыток'
	);

	protected $_messageVariables = array(
		'last_tries' => '_last_tries'
	);

	// количество неудачных попыток до бана по ip
	public $_max_tries = 0;
	public $_last_tries = 0;


	public function __construct($options = array()) {
		if (!is_array($options)) {
			$options = func_get_args();
			$temp['max_tries'] = array_shift($options);

			$options = $temp;
		}

		if (!array_key_exists('max_tries', $options)) {
			$options['max_tries'] = 0;
		}
		$this->setMaxTries($options['max_tries']);
	}

	public function setMaxTries($value) {
		$this->_max_tries = $value;
	}

	public function getMaxTries() {
		return $this->_max_tries;
	}


	function isValid($value) {

		$namespace = Config::getInstance()->captcha->namespace;
		$session = new Zend_Session_Namespace($namespace);
		$sessValue = $session->$namespace;
		$session->$namespace = '';

		$this->_setValue($value);

		if ($this->_caseIgnore) {
			$value = strtoupper($value);
			$sessValue = strtoupper($sessValue);
		}

		if (empty($sessValue) || empty($value) || strcmp($sessValue, $value) != 0) {
			$this->_error(self::INVALID);

			if ($this->getMaxTries() != 0) {
				$this->_last_tries = ($this->_last_tries) > 0 ? --$this->_last_tries : 0;
				$this->_error(self::LAST_TRIES);
			}
		}

		if (count($this->_messages)) {
			return false;
		} else {
			return true;
		}
	}

	function setCaseIgnore($ignore) {
		$this->_caseIgnore = $ignore;
	}
}
